<template>
  <div class="commonBoxmp">
    <TableV2
      selection
      @selection-change="handleselectionChange"
      :columns="state.columnData"
      dataKey="data"
      :data="state.tableData"
      :tableOptions="{
        rowKey: 'menuId',
        border: true,
        treeProps: {
          children: 'children',
          hasChildren: 'hasChildren',
        },
      }"
    >
      <template #tableHeader>
        <div class="jcb aic w100">
          <el-button type="primary" @click="handleAdd">添加菜单</el-button>
        </div>
      </template>
      <template #operation>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-link
              size="mini"
              type="primary"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:menu:edit']"
              >修改</el-link
            >
            <el-link
              size="mini"
              type="primary"
              class="mx5"
              @click="handleAdd(scope.row)"
              v-hasPermi="['system:menu:add']"
              >新增</el-link
            >
            <el-link
              size="mini"
              type="primary"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:menu:remove']"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </template>
    </TableV2>

    <el-dialog
      v-model="state.userVisible"
      :title="state.title"
      width="50%"
      destroy-on-close
      center
    >
      <el-form
        ref="ruleFormRef"
        :model="state.form"
        :rules="state.rules"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="上级菜单" prop="parentId">
              <el-cascader
                :options="state.menuOptions"
                v-model="state.form.parentId"
                class="w100"
                :props="{
                  checkStrictly: true,
                  emitPath: false,
                  value: 'menuId',
                  label: 'menuName',
                }"
                clearable
                @change="handleCascader"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="state.form.menuType">
                <el-radio label="M">目录</el-radio>
                <el-radio label="C">菜单</el-radio>
                <el-radio label="F">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-col :span="24" v-if="state.form.menuType != 'F'">
          <el-form-item label="菜单图标">
            <IconSelect class="w100" v-model="state.form.icon" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="菜单名称" prop="menuName">
            <el-input
              v-model="state.form.menuName"
              placeholder="请输入菜单名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示排序" prop="orderNum">
            <el-input-number
              v-model="state.form.orderNum"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="state.form.menuType != 'F'">
          <el-form-item prop="isFrame">
            <template #label>
              <div class="aic">
                <el-tooltip
                  content="选择是外链则路由地址需要以`http(s)://`开头"
                  placement="top"
                >
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
                是否外链
              </div>
            </template>
            <el-radio-group v-model="state.form.isFrame">
              <el-radio label="0">是</el-radio>
              <el-radio label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="state.form.menuType != 'F'">
          <el-form-item prop="path">
            <template #label>
              <div class="aic">
                <el-tooltip
                  content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头"
                  placement="top"
                >
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
                路由地址
              </div>
            </template>
            <el-input v-model="state.form.path" placeholder="请输入路由地址" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="state.form.menuType == 'C'">
          <el-form-item prop="component">
            <template #label>
              <div class="aic">
                <el-tooltip
                  content="访问的组件路径，如：`system/user/index`，默认在`views`目录下"
                  placement="top"
                >
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
                组件路径
              </div>
            </template>
            <el-input
              v-model="state.form.component"
              placeholder="请输入组件路径"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="state.form.menuType != 'M'">
          <el-form-item prop="perms">
            <el-input
              v-model="state.form.perms"
              placeholder="请输入权限标识"
              maxlength="100"
            />
            <template #label>
              <div class="aic">
                <el-tooltip
                  content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"
                  placement="top"
                >
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
                权限字符
              </div>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="state.form.menuType == 'C'">
          <el-form-item prop="query">
            <el-input
              v-model="state.form.query"
              placeholder="请输入路由参数"
              maxlength="255"
            />
            <template #label>
              <div class="aic">
                <el-tooltip
                  content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`'
                  placement="top"
                >
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
                路由参数
              </div>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="state.form.menuType == 'C'">
          <el-form-item prop="isCache">
            <template #label>
              <div class="aic">
                <el-tooltip
                  content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致"
                  placement="top"
                >
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
                是否缓存
              </div>
            </template>
            <el-radio-group v-model="state.form.isCache">
              <el-radio label="0">缓存</el-radio>
              <el-radio label="1">不缓存</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="state.form.menuType != 'F'">
          <el-form-item prop="visible">
            <template #label>
              <div class="aic">
                <el-tooltip
                  content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问"
                  placement="top"
                >
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
                显示状态
              </div>
            </template>
            <el-radio-group v-model="state.form.visible">
              <el-radio
                v-for="dict in dict.sys_show_hide"
                :key="dict.value"
                :label="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="state.form.menuType != 'F'">
          <el-form-item prop="status">
            <template #label>
              <div class="aic">
                <el-tooltip
                  content="选择停用则路由将不会出现在侧边栏，也不能被访问"
                  placement="top"
                >
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
                菜单状态
              </div>
            </template>
            <el-radio-group v-model="state.form.status">
              <el-radio
                v-for="dict in dict.sys_normal_disable"
                :key="dict.value"
                :label="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.userVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import { ref, reactive, getCurrentInstance, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import Column from "/@ts/components/table/Column";
import selectDict from "/@/components/selectDict/index.vue";

import IconSelect from "/@/components/IconSelect/index.vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import {
  listMenu,
  getMenu,
  delMenu,
  addMenu,
  updateMenu,
} from "../../../axios/urlApi/system/menu";
import DictTag from "/@/components/DictTag/index.vue";
import formatTool from "/@ts/hooks/format";
const router = useRouter();
const route = useRoute();
const { parseTime, addDateRange, handleTree, getDict } = formatTool();


let dict: any = reactive({
  sys_normal_disable: [],
  sys_show_hide: [],
});
const state: any = reactive({
  menuOptions: [],
  // 表格基础配置 start
  title: "",
  form: {},
  userVisible: false,
  // 表单校验
  rules: {
    menuName: [
      { required: true, message: "菜单名称不能为空", trigger: "blur" },
    ],
    orderNum: [
      { required: true, message: "菜单顺序不能为空", trigger: "blur" },
    ],
    path: [{ required: true, message: "路由地址不能为空", trigger: "blur" }],
  },
  dateRange: [], //时间范围筛选

  height: 0,
  tableData: [],
  columnData: [
    {
      label: "菜单名称",
      prop: "menuName",
      visible: true,
    },
    {
      label: "图标",
      prop: "icon",
      visible: true,
    },
    {
      label: "排序",
      prop: "orderNum",
      visible: true,
    },

    {
      label: "权限标识",
      prop: "perms",
      visible: true,
    },
    {
      label: "组件路径",
      visible: true,
      prop: "component",
    },
    {
      label: "状态",
      prop: "status",
      visible: true,
      render: ({ row }: any) => {
        return (
          <DictTag
            values={row.status}
            dataType="primary"
            options={dict.sys_job_status}
          ></DictTag>
        );
      },
    },
    {
      label: "创建时间",
      prop: "createTime",
      visible: true,
    },
  ],
  loading: false,
  // 表格基础配置 end
});
// 表格基础配置 start
const pageInfo = reactive<PageInfoConfig>({
  currentPage: 1,
  total: 10,
  pageSize: 10,
  pageSizes: [10, 20, 30, 40],
  layout: "total, prev, pager, next,sizes",
});
const queryParams: any = reactive({
  pageNum: 1,
  pageSize: 10,
  deptId: undefined,
});
const getCurrentColumns = (data: Column[]) => {
  state.columnData = data;
};

const handleSizeChange = (size: number) => {
  pageInfo.pageSize = size;
  getList();
};
const handleCurrentChange = (page: number) => {
  pageInfo.currentPage = page;
  getList();
};
const handleselectionChange = () =>{
  
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate();
  if (state.form.menuId != undefined) {
    console.log('state.form :>> ', state.form);
    state.form.parentId = state.form.parentId==undefined?0:state.form.parentId
    updateMenu(state.form).then((response: ResponseConfig) => {
      ElMessage.success("修改成功");
      state.userVisible = false;
      getList();
    });
  } else {
    addMenu(state.form).then((response: ResponseConfig) => {
      ElMessage.success("新增成功");
      state.userVisible = false;
      getList();
    });
  }
};
const handleDelete = (row: any) => {
  const userIds = row.menuId;
  ElMessageBox.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
    .then(function () {
      return delMenu(userIds);
    })
    .then(() => {
      ElMessage.success("删除成功");
      getList();
    })
    .catch(function () {});
};
/** 修改按钮操作 */
const handleUpdate = (row: any) => {
  const menuId = row.menuId;
  getMenu(menuId).then((response: ResponseConfig) => {
    state.title = "修改菜单";
    state.form = response.data;
    state.userVisible = true;
  });
};
const handleAdd = (row: any) => {
  getTreeselect();
  state.userVisible = true;
  state.title = "添加菜单";
  state.form = {};
  if (row != null && row.menuId) {
    state.form.parentId = row.menuId;
  } else {
    state.form.parentId = 0;
  }
};
// 表格基础配置 end
const handleCascader = (val: any) => {
};
//查询列表
const getList = () => {
  state.loading = true;
  queryParams.pageNum = pageInfo.currentPage;
  queryParams.pageSize = pageInfo.pageSize;
  listMenu(addDateRange(queryParams, state.dateRange)).then(
    (response: ResponseConfig) => {
      state.tableData = handleTree(response.data, "menuId");
      state.loading = false;
    },
  );
};

const getTreeselect = () => {
  listMenu().then((response: ResponseConfig) => {
    state.menuOptions = [];
    const menu = { menuId: 0, menuName: "主类目", children: [] };
    menu.children = handleTree(response.data, "menuId");
    state.menuOptions.push(menu);
  });
};

const ruleFormRef = ref<FormInstance>();

onMounted(async () => {
  getList();
  getTreeselect();
  dict.sys_job_status = await getDict("sys_job_status");
  dict.sys_normal_disable = await getDict("sys_normal_disable");
  dict.sys_show_hide = await getDict("sys_show_hide");
});
</script>

<style scoped lang="scss"></style>
